package com.innovation.ic.im.end.web.thread;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.innovation.ic.im.end.base.model.im_erp9.Message;
import com.innovation.ic.im.end.base.pojo.constant.MessageType;
import com.innovation.ic.im.end.base.pojo.enums.ReadStatusEnum;
import com.innovation.ic.im.end.base.service.helper.ServiceImplHelper;
import com.innovation.ic.im.end.base.thread.AbstractThread;
import com.innovation.ic.im.end.base.thread.web.SendRabbitMqMessageThread;
import com.innovation.ic.im.end.base.vo.im_erp9.LoginTypeVo;
import com.innovation.ic.im.end.base.vo.im_erp9.MessageVo;
import com.innovation.ic.im.end.base.vo.im_erp9.SendMessageVo;
import com.innovation.ic.im.end.web.endpoint.Endpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import javax.websocket.Session;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @desc   给自己发送消息处理类
 * @author linuo
 * @time   2022年8月16日14:10:23
 */
public class SendSelfMessageThread extends AbstractThread implements Runnable {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private String urlPrefix;

    private String exchange;

    private Integer integration;

    private List<Integer> loginTypeList;

    private Map<String, Endpoint> onlineMap;

    public SendSelfMessageThread(Message message, Map<String, Endpoint> onlineMap, MessageVo messageVo, String exchange, List<Integer> loginTypeList, Integer integration) {
        this.message = message;
        this.onlineMap = onlineMap;
        this.messageVo = messageVo;
        this.exchange = exchange;
        this.loginTypeList = loginTypeList;
        this.integration = integration;
    }

    public SendSelfMessageThread(Message message, Map<String, Endpoint> onlineMap, MessageVo messageVo, String exchange, List<Integer> loginTypeList, String urlPrefix, Integer integration) {
        this.message = message;
        this.onlineMap = onlineMap;
        this.messageVo = messageVo;
        this.urlPrefix = urlPrefix;
        this.exchange = exchange;
        this.loginTypeList = loginTypeList;
        this.integration = integration;
    }

    public SendSelfMessageThread() {}

    @Override
    public void run() {
        // 给自己发送消息
        sendMsgToSelf();

        // 推送websocket消息
        if(loginTypeList != null && loginTypeList.size() > 0){
            // 给自己推送一条补充了id的消息供前端展示
            for (int i = 0; i < loginTypeList.size(); i++) {
                LoginTypeVo loginTypeVo = new LoginTypeVo(messageVo.getFromUserAccount(), loginTypeList.get(i));
                String usernameStr = JSONObject.toJSON(loginTypeVo).toString();

                if(null != onlineMap.get(usernameStr) && null != onlineMap.get(usernameStr).session){
                    Session session = onlineMap.get(usernameStr).session;
                    synchronized (session) {
                        if (session.isOpen()) {
                            if(messageVo.getType() != null && messageVo.getType().intValue() == MessageType.PICTURE && !Strings.isNullOrEmpty(messageVo.getFilePath())){
                                if(!messageVo.getFilePath().contains(urlPrefix)){
                                    messageVo.setFilePath(urlPrefix + messageVo.getFilePath());
                                }
                            }
                            SendMessageVo sendMessageVo = new SendMessageVo();
                            BeanUtils.copyProperties(messageVo, sendMessageVo);
                            sendMessageVo.setId(message.getId());
                            sendMessageVo.setIntegration(integration);
                            logger.info("sendMessageVo=[{}]", sendMessageVo);
                            session.getAsyncRemote().sendText(JSON.toJSONString(sendMessageVo));
                        }
                    }
                }
            }
        }
    }

    /**
     * 给自己发送消息
     */
    protected void sendMsgToSelf() {
        // 更新chatPair中的最近联系时间
        ServiceImplHelper.getChatPairService().updateLastContactTime(message.getFromUserAccount(), message.getFromUserAccount());

        // 保存消息信息
        message.setRead(ReadStatusEnum.READ.getCode());
        Integer id = ServiceImplHelper.getMessageService().saveMessage(message).getResult();
        if(id != null){
            message.setId(id);
        }

        // 推送rabbitMq消息
        List<String> list = new ArrayList<>();
        list.add(message.getFromUserAccount());
        SendRabbitMqMessageThread sendRabbitMqMessageThread = new SendRabbitMqMessageThread(list, exchange);
        threadPoolManager.execute(sendRabbitMqMessageThread);
    }
}